package com.ihighest.app.infox.adapter;

import org.json.JSONArray;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.infox.R;

public class SearchListAdapter extends BaseAdapter {

	static final String TAG = "SearchListAdapter";
	Context context;
	JSONArray array;
	LayoutInflater inflate;

	public SearchListAdapter(Context context) {
		this.context = context;
		this.inflate = LayoutInflater.from(context);
	}

	public JSONArray set(JSONArray jsonArray) {
		this.array = jsonArray;
		return this.array;
	}

	public JSONArray append(JSONArray jsonArray) {
		try {
			this.array = AppKit.joinJSONArray(array, jsonArray);
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		return this.array;
	}

	@Override
	public int getCount() {
		return array != null ? array.length() : 0;
	}

	@Override
	public Object getItem(int arg0) {
		return arg0;
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(int potision, View contentview, ViewGroup arg2) {
		ViewHolder holder;
		if (contentview == null) {
			holder = new ViewHolder();
			contentview = inflate.inflate(R.layout.infox_activity_search_item, null);
			holder.searchRank = (TextView) contentview.findViewById(R.id.hotsearch_list_ranking);
			holder.searchTitle = (TextView) contentview.findViewById(R.id.search_list_title);
			contentview.setTag(holder);
		} else {
			holder = (ViewHolder) contentview.getTag();
		}
		try {
			holder.searchTitle.setText(array.getJSONObject(potision).getString("key"));
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		holder.searchRank.setText("" + (potision + 1));
		if (potision == 0) {
			holder.searchRank.setBackgroundResource(R.drawable.infox_searchitem_first);
		} else if (potision == 1) {
			holder.searchRank.setBackgroundResource(R.drawable.infox_searchitem_second);
		} else if (potision == 2) {
			holder.searchRank.setBackgroundResource(R.drawable.infox_searchitem_third);
		} else {
			holder.searchRank.setBackgroundResource(R.drawable.infox_searchitem_others);
		}
		return contentview;
	}

	class ViewHolder {
		TextView searchRank;
		TextView searchTitle;
	}
}
